<template>
    <div class="layout-padding">
        <el-form :inline="true" ref="queryRef" :model="queryParams" label-width="120px">
            <el-form-item label="区段：">
                <el-tree-select v-model="queryParams.section" :data="dataSource"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                    :render-after-expand="false" check-strictly @change="treeChange">
                </el-tree-select>
            </el-form-item>
            <el-form-item label="工区：">
                <el-tree-select v-model="queryParams.workArea" :data="dataSourceArea"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                    :render-after-expand="false" check-strictly>
                </el-tree-select>
            </el-form-item>
            <el-form-item label="时间：">
                <el-date-picker v-model="queryParams.time" type="datetimerange" range-separator="—"
                    start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss" @change="calendarChange" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button type="primary" @click="handleExport">导出</el-button>
                <el-button type="primary" @click="handleImport">导入</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="list">
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column label="区段" align="center" prop="sectionName" />
            <el-table-column label="工区" align="center" prop="workAreaName" />
            <el-table-column label="看守时间" align="center" prop="guardTime" />
            <el-table-column label="看守人" align="center" prop="guardUser" >
                <template #default="scope">
                    {{ handleUser(scope.row.guardUser) }}
                </template>
            </el-table-column>
            <el-table-column label="看守地点" align="center" prop="guardPlace" />

            <el-table-column label="现场情况" align="center" prop="situation" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 详情对话框 -->
        <el-dialog :title="title" v-model="open" width="780px" append-to-body>
            <el-form ref="configRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="区段：" prop="section">
                            <el-tree-select v-model="form.section" :data="dataSource"
                                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                :render-after-expand="false" check-strictly @change="treeChange">
                            </el-tree-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工区：" prop="workArea">
                            <el-tree-select v-model="form.workArea" :data="dataSourceArea"
                                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                :render-after-expand="false" check-strictly @change="treeGauge">
                            </el-tree-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="看守人：" prop="guardUser">
                            <el-select v-model="form.guardUser" placeholder="请选择" clearable>
                                <el-option v-for="item in options" :key="item.userId" :label="item.userName"
                                    :value="item.userId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="看守时间：" prop="guardTime">
                            <el-date-picker v-model="form.guardTime" placeholder="请输入参数"
                                value-format="YYYY-MM-DD HH:mm:ss" type="datetime" format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="看守地点：" prop="guardPlace">
                            <!-- <el-input v-model="form.guardPlace" placeholder="请输入参数" /> -->
                            <el-select v-model="form.guardPlace" placeholder="请选择" >
                                <el-option v-for="(item,index) in optionsControl" :key="index" :label="item.mileage" :value="item.mileage" />
                                </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="现场情况" prop="situation">
                    <el-input v-model="form.situation" type="textarea" placeholder="请输入内容" />
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">保存</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 附图 -->
        <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
            <div v-for="item in ImageUrlList" :key="item" style="margin-bottom: 10px;">
                <img :src="item" style="display: block; max-width: 100%; margin: 0 auto" />
            </div>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { listSiteGuard, getSiteGuard, addSiteGuard, updateSiteGuard, delSiteGuard } from "@/api/system/guard.js";
import { getTreeList, getDeptBy, getPersonBy,getControl } from "@/api/work";
import { getToken } from '@/utils/auth'
import { number } from "echarts";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();


/*** 导入参数 */
const upload = reactive({
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/siteGuard/importData',
})

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        submited: true,
        sectionName: undefined,
        workAreaName: undefined,
        time: [],
        params: {
            startTime: undefined,
            endTime: undefined,
        }
    },
    rules: {
        // section: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
    }
});
const { queryParams, form, rules } = toRefs(data);

const loading = ref(true);
const list = ref([]);
const total = ref(0);
const open = ref(false);
const dialogVisible = ref(false);
const title = ref("看守详情");

const uploadFileFlag = ref(false);
const ImageUrlList = ref([]);

const optionsControl = ref([])
  function getOptions() {
    getControl().then(res => {
      optionsControl.value = res.rows
    })
  }
  getOptions()
//区段数据
const dataSource = ref([])
const dataSourceArea = ref([])
const options = ref([])
function getTree() {
    getTreeList().then(res => {
        dataSource.value = res.data
    })
}
getTree()
function treeChange(id) {
    queryParams.value.workArea = ''
    form.value.workArea = ''
    form.value.guardUser = ''
    options.value = []
    dataSourceArea.value =[]
    getDeptBy({
        parentId: id
    }).then(res => {
        dataSourceArea.value = res.data
    })
}

function treeGauge(id) {
    form.value.guardUser = ''
    getPersonBy({
        deptId: id
    }).then(res => {
        options.value = res.rows
        options.value.forEach(item=>{
            item.userId = String(item.userId)

        })

    })
}
const allUser = ref([])
//获取全部人
function treeGaugeAll() {
    form.value.guardUser = ''
    getPersonBy({
        deptId: ''
    }).then(res => {
        allUser.value = res.rows
    })
}
treeGaugeAll()

//显示人名
function handleUser(userId) {
    if (userId == null || userId == '' || userId == undefined) {
        return ''
    }
    let userName = ''
    allUser.value.forEach(item => {
        if (item.userId == userId) {
            userName = item.userName
        }
    })
    return userName == '' ? userId : userName
}

/** 查询公告列表 */
function getList() {
    loading.value = true;
    listSiteGuard(queryParams.value).then(response => {
        list.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}


/** 搜索按钮操作 */
function handleQuery() {

    if (queryParams.value.time !== null && queryParams.value.time.length > 1) {
        queryParams.value.params.startTime = queryParams.value.time[0];
        queryParams.value.params.endTime = queryParams.value.time[1];
    }
    queryParams.value.pageNum = 1;
    getList();
}

/** 查看按钮操作 */
function handleView(row) {
    dialogVisible.value = true
    if (row.picUrl.indexOf(",") == -1) {
        ImageUrlList.value.push(row.picUrl)
    } else {
        ImageUrlList.value = row.picUrl.split(",")
    }
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    uploadFileFlag.value = true;
    title.value = "添加看守";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    if(row.section != undefined && row.section != null &&  row.section != "" ){
        treeChange(row.section)
    }
    if(row.workArea != undefined && row.workArea != null &&  row.workArea != "" ){
        treeGauge(row.workArea) 
    }
    nextTick(()=>{
        const id = row.id;
        getSiteGuard(id).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改看守";
            uploadFileFlag.value = false;
        });
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.id;
    proxy.$modal.confirm('是否确认删除该数据项？').then(function () {
        return delSiteGuard(id);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}

/** 表单重置 */
function reset() {
    form.value.workArea = ''
    form.value.guardUser = ''
    options.value =[]
    dataSourceArea.value =[]
    form.value = {
        sectionName: undefined,
        workAreaName: undefined,
        params: {
            startTime: undefined,
            endTime: undefined,
        }
    };
    proxy.resetForm("configRef");
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["configRef"].validate(valid => {
        if (valid) {
            form.value.submited = 1;
            if (form.value.id != undefined) {
                updateSiteGuard(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addSiteGuard(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}


function calendarChange(value) {
    if (value == null) {
        queryParams.value.params.startTime = undefined;
        queryParams.value.params.endTime = undefined;
    }
}


/** 导出按钮操作 */
function handleExport() {
    proxy.download("sjgtw-emergency/siteGuard/export", {
        ...queryParams.value
    }, `重点地段看守管理${new Date().getTime()}.xlsx`);
}


/** 导入按钮操作 */
function handleImport() {
    upload.title = '导入'
    upload.open = true
}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}


/** 下载模板操作 */
function importTemplate() {
    proxy.download('sjgtw-emergency/siteGuard/downloadTemplate', {}, `template_${new Date().getTime()}.xlsx`)
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    if (response.code == 200) {
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })

    } else {
        proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
    }
    getList()
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}

nextTick(() => {
    getList();
})
</script>

<style lang="scss" scoped>
.layout-padding {
    padding: 10px;
}
</style>
